package cn.npe2.scaffolding.utils;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import lombok.experimental.UtilityClass;

/**
 * 数据模型操作类
 *
 * @author: Echan
 * @since: 2021-12-04 12:57
 */

@UtilityClass
public class OperationUtil {

    /**
     * 对某个字段过滤重复数据 - TreeSet方式处理
     *
     * @param collect
     * @param keyExtractor
     * @param <T>
     * @param <U>
     * @return
     */
    public <T, U extends Comparable<? super U>> Stream<T> distinctByField(
            Collection<T> collect, Function<? super T, ? extends U> keyExtractor) {
        return collect.stream().collect(collectingAndThen(toCollection(() ->
                new TreeSet<>(Comparator.comparing(keyExtractor))), ArrayList::new)).stream();
    }

    /**
     * 对某个字段过滤重复数据 - Map方式处理
     *
     * @param keyExtractor
     * @param <T>
     * @param <R>
     * @return
     */
    public <T, R> Predicate<T> distinctByKey(Function<? super T, R> keyExtractor) {
        Map<Object, Boolean> map = new ConcurrentHashMap<>(16);
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}
